<template>
  <div class="home-container">
    <!-- 顶部 Banner -->
    <div class="welcome-banner">
      <div class="banner-content">
        <h1>问卷博客管理平台</h1>
        <p>分享知识，共同进步</p>
        <div class="banner-actions">
          <button class="primary-btn" @click="$router.push('/blog/edit')">开始写作</button>
          <button class="secondary-btn" @click="$router.push('/questionnaires')">发布问卷</button>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧内容区 -->
      <div class="left-section">
        <!-- 热门博客 -->
        <div class="section">
          <div class="section-header">
            <h2>热门博客</h2>
            <a class="more-link" @click="$router.push('/blog')">查看更多 ></a>
          </div>
          <div class="blog-list">
            <div v-for="blog in blogs" :key="blog.id" 
                 class="blog-item"
                 @click="viewBlog(blog.id)">
              <div class="blog-main">
                <h3>{{ blog.title }}</h3>
                <p class="excerpt">{{ blog.content.substring(0, 150) }}...</p>
                <div class="blog-meta">
                  <span class="author">
                    <img :src="blog.authorAvatar || '/default-avatar.png'" class="avatar">
                    {{ getAuthorName(blog) }}
                  </span>
                  <span class="time">{{ formatDate(blog.createTime) }}</span>
                  <span class="views"><i class="fa fa-eye"></i> {{ blog.views || 0 }}</span>
                  <span class="likes"><i class="fa fa-heart"></i> {{ blog.likes?.length || 0 }}</span>
                </div>
              </div>
              <div class="blog-cover" v-if="blog.coverImage">
                <img :src="blog.coverImage" alt="封面">
              </div>
            </div>
          </div>
        </div>

        <!-- 最新问卷 -->
        <div class="section">
          <div class="section-header">
            <h2>最新问卷</h2>
            <a class="more-link" @click="$router.push('/questionnaires')">查看更多 ></a>
          </div>
          <div class="questionnaire-list">
            <div v-for="q in activeQuestionnaires" :key="q.id" 
                 class="questionnaire-item"
                 @click="$router.push(`/fill/${q.id}`)">
              <div class="questionnaire-main">
                <h3>{{ q.title }}</h3>
                <div class="questionnaire-meta">
                  <span class="creator">
                    <img :src="q.creatorAvatar || '/default-avatar.png'" class="avatar">
                    {{ getCreatorName(q) }}
                  </span>
                  <span class="time">
                    <i class="fa fa-clock-o"></i>
                    截止时间: {{ formatDate(q.deadline) }}
                  </span>
                </div>
              </div>
              <div class="status-tag">进行中</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧边栏 -->
      <div class="right-sidebar">
        <!-- 用户信息卡片 -->
        <div class="user-card" v-if="currentUser.username">
          <img :src="currentUser.avatarUrl || '/default-avatar.png'" class="user-avatar">
          <h3>{{ currentUser.nickname || currentUser.username }}</h3>
          <div class="user-stats">
            <div class="stat-item">
              <div class="stat-value">{{ userStats.blogs }}</div>
              <div class="stat-label">博客</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ userStats.questionnaires }}</div>
              <div class="stat-label">问卷</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ userStats.likes }}</div>
              <div class="stat-label">获赞</div>
            </div>
          </div>
        </div>

        <!-- 活跃作者 -->
        <div class="section">
          <h3>活跃作者</h3>
          <div class="active-authors">
            <div v-for="author in activeAuthors" :key="author.username" class="author-item">
              <img :src="author.avatarUrl || '/default-avatar.png'" class="author-avatar">
              <div class="author-info">
                <div class="author-name">{{ author.nickname || author.username }}</div>
                <div class="author-stats">
                  <span>文章 {{ author.blogCount }}</span>
                  <span>获赞 {{ author.likeCount }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 热门标签 -->
        <div class="section">
          <h3>热门标签</h3>
          <div class="tag-cloud">
            <span v-for="tag in hotTags" 
                  :key="tag.name" 
                  class="tag"
                  @click="viewTagBlogs(tag.name)"
                  :style="{ fontSize: tag.weight + 'px' }">
              {{ tag.name }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HomeComponent',
  data() {
    return {
      blogs: [],
      activeQuestionnaires: [],
      activeAuthors: [],
      currentUser: JSON.parse(localStorage.getItem('currentUser') || '{}'),
      userStats: {
        blogs: 0,
        questionnaires: 0,
        likes: 0
      },
      hotTags: []
    }
  },
  methods: {
    getAuthorName(blog) {
      const users = JSON.parse(localStorage.getItem('users') || '[]')
      const author = users.find(user => user.username === blog.author)
      return author?.nickname || blog.author
    },
    getCreatorName(questionnaire) {
      const users = JSON.parse(localStorage.getItem('users') || '[]')
      const creator = users.find(user => user.username === questionnaire.creator)
      return creator?.nickname || questionnaire.creator || '未知用户'
    },
    loadBlogs() {
      const blogs = JSON.parse(localStorage.getItem('blogs') || '[]')
      const users = JSON.parse(localStorage.getItem('users') || '[]')
      
      // 获取已发布的博客并添加作者信息
      this.blogs = blogs
        .filter(blog => blog.approved)
        .map(blog => {
          const author = users.find(user => user.username === blog.author)
          return {
            ...blog,
            authorAvatar: author?.avatarUrl || '/default-avatar.png'  // 添加作者头像
          }
        })
        .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
        .slice(0, 5) // 只显示最新的5篇
      this.loadHotTags()
    },
    loadQuestionnaires() {
      const questionnaires = JSON.parse(localStorage.getItem('questionnaire') || '[]')
      const users = JSON.parse(localStorage.getItem('users') || '[]')
      
      // 获取发布中的问卷并添加创建者信息
      this.activeQuestionnaires = questionnaires
        .filter(q => q.state === 1 && q.deadline) // 只显示有截止时间的发布中问卷
        .map(q => {
          const creator = users.find(user => user.username === q.creator)
          return {
            ...q,
            creatorAvatar: creator?.avatarUrl || '/default-avatar.png'
          }
        })
        .sort((a, b) => new Date(b.time) - new Date(a.time))
        .slice(0, 5)
    },
    loadActiveAuthors() {
      const users = JSON.parse(localStorage.getItem('users') || '[]')
      const blogs = JSON.parse(localStorage.getItem('blogs') || '[]')
      
      // 统计作者数据
      const authorStats = {}
      blogs.forEach(blog => {
        if (!blog.approved) return
        
        if (!authorStats[blog.author]) {
          authorStats[blog.author] = {
            blogCount: 0,
            likeCount: 0
          }
        }
        authorStats[blog.author].blogCount++
        authorStats[blog.author].likeCount += blog.likes?.length || 0
      })
      
      // 生成活跃作者列表
      this.activeAuthors = users
        .map(user => ({
          ...user,
          blogCount: authorStats[user.username]?.blogCount || 0,
          likeCount: authorStats[user.username]?.likeCount || 0
        }))
        .filter(author => author.blogCount > 0)
        .sort((a, b) => b.blogCount - a.blogCount)
        .slice(0, 5)
    },
    loadUserStats() {
      if (!this.currentUser.username) return
      
      const blogs = JSON.parse(localStorage.getItem('blogs') || '[]')
      const questionnaires = JSON.parse(localStorage.getItem('questionnaire') || '[]')
      
      this.userStats = {
        blogs: blogs.filter(b => b.author === this.currentUser.username).length,
        questionnaires: questionnaires.filter(q => q.creator === this.currentUser.username).length,
        likes: blogs
          .filter(b => b.author === this.currentUser.username)
          .reduce((sum, blog) => sum + (blog.likes?.length || 0), 0)
      }
    },
    formatDate(dateString) {
      if (!dateString) return '未设置'
      try {
        const date = new Date(dateString)
        if (isNaN(date.getTime())) return '无效日期'
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch (e) {
        return '无效日期'
      }
    },
    viewBlog(id) {
      this.$router.push({
        name: 'BlogView',
        params: { id: id.toString() }
      })
    },
    loadHotTags() {
      const blogs = JSON.parse(localStorage.getItem('blogs') || '[]')
      const tagStats = {}
      
      // 统计所有标签的使用次数
      blogs.forEach(blog => {
        if (blog.status === 'published' && blog.tags) {
          blog.tags.forEach(tag => {
            tagStats[tag] = (tagStats[tag] || 0) + 1
          })
        }
      })
      
      // 转换为数组并排序
      this.hotTags = Object.entries(tagStats)
        .map(([name, count]) => ({
          name,
          weight: Math.min(20, 14 + Math.floor(count * 1.5)), // 根据使用次数计算字体大小
          count
        }))
        .sort((a, b) => b.count - a.count)
        .slice(0, 20) // 只显示前20个热门标签
    },
    viewTagBlogs(tagName) {
      this.$router.push({
        name: 'BlogList',
        query: { tag: tagName }
      })
    }
  },
  created() {
    this.loadBlogs()
    this.loadQuestionnaires()
    this.loadActiveAuthors()
    this.loadUserStats()
  }
}
</script>

<style lang="scss" scoped>
.home-container {
  .welcome-banner {
    background: linear-gradient(135deg, #ee7419, #ff9d4d);
    padding: 60px 0;
    color: white;
    text-align: center;
    margin-bottom: 40px;

    .banner-content {
      max-width: 800px;
      margin: 0 auto;
      
      h1 {
        font-size: 36px;
        margin-bottom: 16px;
        font-weight: 600;
      }

      p {
        font-size: 18px;
        opacity: 0.9;
        margin-bottom: 32px;
      }

      .banner-actions {
        display: flex;
        gap: 20px;
        justify-content: center;

        button {
          padding: 12px 32px;
          border-radius: 24px;
          font-size: 16px;
          cursor: pointer;
          transition: all 0.3s ease;

          &.primary-btn {
            background: white;
            color: #ee7419;
            border: none;

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            }
          }

          &.secondary-btn {
            background: transparent;
            color: white;
            border: 2px solid white;

            &:hover {
              background: rgba(255,255,255,0.1);
            }
          }
        }
      }
    }
  }

  .main-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 40px;

    .section {
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0,0,0,0.08);
      padding: 24px;
      margin-bottom: 24px;

      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        h2 {
          font-size: 20px;
          font-weight: 600;
          color: #333;
        }

        .more-link {
          color: #666;
          cursor: pointer;
          
          &:hover {
            color: #ee7419;
          }
        }
      }
    }

    .blog-list {
      .blog-item {
        display: flex;
        gap: 20px;
        padding: 20px 0;
        border-bottom: 1px solid #eee;
        cursor: pointer;

        &:last-child {
          border-bottom: none;
        }

        &:hover {
          h3 {
            color: #ee7419;
          }
        }

        .blog-main {
          flex: 1;

          h3 {
            font-size: 18px;
            color: #333;
            margin-bottom: 12px;
            transition: color 0.3s;
          }

          .excerpt {
            color: #666;
            font-size: 14px;
            line-height: 1.6;
            margin-bottom: 12px;
          }

          .blog-meta {
            display: flex;
            align-items: center;
            gap: 16px;
            color: #999;
            font-size: 13px;

            .author {
              display: flex;
              align-items: center;
              gap: 6px;

              .avatar {
                width: 24px;
                height: 24px;
                border-radius: 50%;
              }
            }

            i {
              margin-right: 4px;
            }
          }
        }

        .blog-cover {
          width: 200px;
          height: 120px;
          border-radius: 8px;
          overflow: hidden;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
      }
    }

    .right-sidebar {
      .user-card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.08);
        padding: 24px;
        text-align: center;
        margin-bottom: 24px;

        .user-avatar {
          width: 80px;
          height: 80px;
          border-radius: 50%;
          margin-bottom: 16px;
        }

        h3 {
          font-size: 18px;
          color: #333;
          margin-bottom: 16px;
        }

        .user-stats {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 12px;

          .stat-item {
            .stat-value {
              font-size: 20px;
              font-weight: 600;
              color: #333;
            }

            .stat-label {
              font-size: 13px;
              color: #999;
            }
          }
        }
      }

      .active-authors {
        .author-item {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 12px 0;
          border-bottom: 1px solid #eee;

          &:last-child {
            border-bottom: none;
          }

          .author-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
          }

          .author-info {
            flex: 1;

            .author-name {
              font-size: 14px;
              color: #333;
              margin-bottom: 4px;
            }

            .author-stats {
              font-size: 12px;
              color: #999;

              span {
                margin-right: 12px;
              }
            }
          }
        }
      }

      .tag-cloud {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        padding: 15px;

        .tag {
          padding: 4px 12px;
          background: #f5f5f5;
          border-radius: 16px;
          color: #666;
          cursor: pointer;
          transition: all 0.3s ease;
          text-decoration: none;

          &:hover {
            background: #ee7419;
            color: white;
            transform: scale(1.05);
          }
        }
      }
    }
  }

  .questionnaire-list {
    .questionnaire-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 0;
      border-bottom: 1px solid #eee;
      cursor: pointer;
      transition: all 0.3s ease;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        h3 {
          color: #ee7419;
        }
        transform: translateX(5px);
      }

      .questionnaire-main {
        flex: 1;
        min-width: 0;

        h3 {
          font-size: 16px;
          color: #333;
          margin-bottom: 8px;
          transition: color 0.3s;
        }

        .questionnaire-meta {
          display: flex;
          align-items: center;
          gap: 16px;
          color: #999;
          font-size: 13px;

          .creator {
            display: flex;
            align-items: center;
            gap: 6px;

            .avatar {
              width: 24px;
              height: 24px;
              border-radius: 50%;
            }
          }

          .time {
            display: flex;
            align-items: center;
            gap: 4px;
            
            i {
              font-size: 14px;
            }
          }
        }
      }

      .status-tag {
        padding: 4px 12px;
        background: #e6f7ff;
        color: #1890ff;
        border-radius: 12px;
        font-size: 12px;
      }
    }
  }
}
</style>